package com.ypc.webdemo.dao.entity;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ypc.plugininterface.dto.xml.ServiceDTO;
import com.ypc.plugininterface.dto.xml.VendorDTO;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author yinpengcheng
 * @Date 2023/7/21
 */
@Accessors(chain = true)
@Data
@Table
@Entity
public class Plugin {
    @Id
    private String id;
    @Column
    private String name;
    @Column(nullable = false)
    private String fileName;
    /**
     * 加载状态：installed, uninstalled
     *
     * @see com.ypc.webdemo.common.PluginStatusEnum
     */
    @Column(nullable = false)
    private String status;
    @Column(columnDefinition = "text")
    private String description;
    @Column(nullable = false)
    private Date created;
    private String key;
    private String version;
    @Transient
    private VendorDTO vendor;
    @JsonIgnore
    @Column(columnDefinition = "text")
    private String vendorJson;
    @Column(columnDefinition = "text")
    private String changeNotes;
    @Transient
    private List<ServiceDTO> services;
    @JsonIgnore
    @Column(columnDefinition = "text")
    private String servicesJson;
    @Column(columnDefinition = "text")
    private String message;

    public VendorDTO getVendor() {
        return vendor = StringUtils.hasLength(vendorJson) ? JSON.parseObject(vendorJson, VendorDTO.class) : null;
    }

    public Plugin setVendor(VendorDTO vendor) {
        this.vendor = vendor;
        this.vendorJson = Optional.ofNullable(vendor).map(JSON::toJSONString).orElse(null);
        return this;
    }

    public List<ServiceDTO> getServices() {
        return services = StringUtils.hasLength(servicesJson) ? JSON.parseArray(servicesJson, ServiceDTO.class) : Collections.emptyList();
    }

    public Plugin setServices(List<ServiceDTO> services) {
        this.services = services;
        this.servicesJson = Optional.ofNullable(services).map(JSON::toJSONString).orElse(null);
        return this;
    }
}
